

# 使用装饰器来捕获异常 简化代码
import traceback


def item_exception_wrapper(func):
    def inner(self, response):
        try:
            _obj = func(self, response)
        except KeyError as key_error:
            self.logger.error(
                '当前 item  发生了  {error_type} 异常 , 当前item 页面地址是: {url} , 当前的页面引自于: {ref}'.format(
                    error_type=key_error, url=response.url, ref=bytes.decode(response.request.headers["Referer"])))
            self.logger.info(traceback.format_exc(key_error))
        except IndexError as index_error:
            self.logger.error(
                '当前 item  发生了  {error_type} 异常 , 当前item 页面地址是: {url} , 当前的页面引自于: {ref} '.format(
                    error_type=index_error, url=response.url, ref=bytes.decode(response.request.headers["Referer"])))
            self.logger.info(traceback.format_exc(index_error))
        except BaseException as e:
            self.logger.error(
                '当前 item  发生了  {error_type} 异常 , 当前item 页面地址是: {url} , 当前的页面引自于: {ref}'.format(
                    error_type=e,url=response.url, ref=bytes.decode(response.request.headers["Referer"])))
            self.logger.info(traceback.format_exc(e))
        else:
            return _obj

    return inner


